/*global pi, window, document */
// 文档事件模块
// 触碰事件和长按事件的处理。
// 非IE浏览器要生成双击事件。支持穿透forelet向下传递鼠标事件。
// 提供标准的拖动事件处理器，按钮事件处理器，右键事件处理器，提示条处理器，forelet自动提升zindex事件处理器，ScrollBar处理器，
// IE 取消默认事件 oEvent.returnValue = false;
// 标准的DOM 取消默认事件 oEvent.preventDefault();
// 键盘事件触发的顺序为：keydown —> keypress —> keyup

pi.mod.define('pi.ui.event', function(pi) {
	"use strict";
	// 定义模块
	var module = {},
	createEventHandler = function(forelet) {
		var eventHandler = {},
		handlerList = pi.event.createHandlerList(),
		preHandlerList = pi.event.createHandlerList();
		eventHandler.handle = function(e) {
			e = pi.html.fixEvent(e, forelet);
			preHandlerList(e);
			return handlerList(e);
		};
		eventHandler.add = function(handler) {
			handlerList.add(handler);
		};
		eventHandler.addPre = function(handler) {
			preHandlerList.add(handler);
		};
		return eventHandler;
	},
	eventType = ["mousedown", "mousemove", "mouseup", "mouseover", "mouseout", "mousewheel", "DOMMouseScroll", "click", "dblclick", "dragstart", "selectstart", "drag", "contextmenu", "rightclick", "longpress"];

	// 创建文档事件处理器表
	module.createHandlerTable = function(forelet) {
		var i, table = {};
		for (i = eventType.length - 1; i >= 0; i--) {
			table[eventType[i]] = createEventHandler(forelet);
		}
		// 将右键事件转发到右键事件列表上
		table.click.add(function(e) {
			if (e.button === 2) {
				return table.rightclick(e);
			}
		});
		return table;
	};
	// 将事件处理器表绑定到指定元素上
	module.bind = function(el, handlerTable) {
		var i, type;
		for (i = eventType.length - 1; i >= 0; i--) {
			type = eventType[i];
			el["on" + type] = handlerTable[type].handle;
		}
	};
	// 解绑文档元素上的事件处理器表
	module.unbind = function(el, handlerTable) {
		var i, type;
		for (i = eventType.length - 1; i >= 0; i--) {
			type = eventType[i];
			delete el["on" + type];
		}
	};

	return module;
});